package com.zheng.controller;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import com.zheng.common.Result;
import com.zheng.config.WyMailConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FlagTerm;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @Copyright (c) 合思技术团队 https://www.hosecloud.com/
 * @Package com.zheng.controller
 * @Project：trans_demo
 * @authur：zhengtianliang@hosecloud.com
 * @date：2025/8/6 15:14
 */

@RestController
@RequestMapping("/aaemail")
public class WyEmailMethodController {
    @Autowired
    private JavaMailSender javaMailSender;

    //发件人邮箱
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private WyMailConfig mailConfig;


    public static EmailVo parseEmail(Message msg) throws MessagingException, IOException {
        Address[] fromAddress = msg.getFrom();
        if(Objects.isNull(fromAddress) || fromAddress.length == 0){
            return null;
        }
        String from = fromAddress[0].toString();
        String subject = msg.getSubject();
        Object content = msg.getContent();
        if (!(content instanceof Multipart)) {
            return null;
        }
        Multipart multipart = (Multipart) content;
        EmailVo emailVo = new EmailVo();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            String disposition = bodyPart.getDisposition();
            if (BodyPart.ATTACHMENT.equalsIgnoreCase(disposition) ||
                    BodyPart.INLINE.equalsIgnoreCase(disposition)) {
                //处理附件
                fillFiles(emailVo, bodyPart);
            }
            else {
                // 处理内容
                fillVo(emailVo, bodyPart);
            }
        }
        return emailVo;
    }

    private static final String FILE_EXT_OFD = "ofd";
    private static final String FILE_EXT_PDF = "pdf";
    /**
     * 补足文件信息
     * @param emailVo
     */
    public static void fillFiles(EmailVo emailVo,BodyPart bodyPart) throws MessagingException, IOException {
        String fileName = bodyPart.getFileName();
        if (!StringUtils.isEmpty(fileName)) {
            String[] fileNames = fileName.split("\\.");
            if(fileNames.length!=2){
                return;
            }
            emailVo.setVoucherNo(fileNames[0]);
            if(fileNames[1].contains(FILE_EXT_OFD)){
                emailVo.setOfdBytes(IOUtils.toByteArray(bodyPart.getInputStream()));
            }
            else if(fileNames[1].contains(FILE_EXT_PDF)){
                emailVo.setPdfBytes(IOUtils.toByteArray(bodyPart.getInputStream()));
            }
        }
    }

    /**
     * 补足基本信息
     * @param emailVo
     * @param bodyPart
     * @throws MessagingException
     * @throws IOException
     */
    public static void fillVo(EmailVo emailVo,BodyPart bodyPart) throws MessagingException, IOException {
        Object content = bodyPart.getContent();
        Multipart multipart = (Multipart) bodyPart.getContent();
        for (int j = 0; j < multipart.getCount(); j++) {
            BodyPart bodyPart1 = multipart.getBodyPart(j);
            String email = bodyPart1.getContent().toString();
            emailVo.setUserName(parseUserName(email));
            emailVo.setOrderNumber(parseOrderNumber(email));
        }
    }
    private static final Pattern REGEX_PATTERN_USER_NAME =
            Pattern.compile("尊敬的 <span style=\"color: #ff764c;\">(.*?)：</span>",
                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    private static final Pattern REGEX_PATTERN_ORDER_NUMBER =
            Pattern.compile("您的订单<span style=\"color: #ff764c; font-size: 14px;\">(.*?)</span>的电子发票已开具",
                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    public static String parseUserName(String content) {
        Matcher matcher = REGEX_PATTERN_USER_NAME.matcher(content);
        while (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }

    public static String parseOrderNumber(String content) {
        Matcher matcher = REGEX_PATTERN_ORDER_NUMBER.matcher(content);
        while (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }
    public static class EmailVo implements Serializable {
        private static final long serialVersionUID = 5382849736692084642L;
        private String userName;
        private String orderNumber;
        private String voucherNo;
        private byte[] ofdBytes;
        private byte[] pdfBytes;
        private Long msgId;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getOrderNumber() {
            return orderNumber;
        }

        public void setOrderNumber(String orderNumber) {
            this.orderNumber = orderNumber;
        }

        public byte[] getOfdBytes() {
            return ofdBytes;
        }

        public void setOfdBytes(byte[] ofdBytes) {
            this.ofdBytes = ofdBytes;
        }

        public byte[] getPdfBytes() {
            return pdfBytes;
        }

        public void setPdfBytes(byte[] pdfBytes) {
            this.pdfBytes = pdfBytes;
        }

        public String getVoucherNo() {
            return voucherNo;
        }

        public void setVoucherNo(String voucherNo) {
            this.voucherNo = voucherNo;
        }

        public Long getMsgId() {
            return msgId;
        }

        public void setMsgId(Long msgId) {
            this.msgId = msgId;
        }

        @Override
        public String toString() {
            return "{\"EmailVo\":{"
                    + "\"userName\":\"" + userName + "\""
                    + ", \"orderNumber\":\"" + orderNumber + "\""
                    + ", \"voucherNo\":\"" + voucherNo + "\""
                    + "}}";
        }
    }


    @GetMapping("/receivePage1")
    public Result receiveUnreadEmailsByPage(@RequestParam(defaultValue = "1") int page,
                                            HttpServletResponse response) {

// 1. 配置IMAP服务器
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imap");
        props.setProperty("mail.imap.host", "imap.163.com");
        props.setProperty("mail.imap.port", "993");
        props.setProperty("mail.imap.ssl.enable", "true");
        props.setProperty("mail.imap.auth", "true");

        // 设置IMAP ID信息
        HashMap<String, String> IAM = new HashMap<>();
        IAM.put("name", "myname");
        IAM.put("version", "1.0.0");
        IAM.put("vendor", "myclient");
        IAM.put("support-email", "testmail@test.com");
        Session session = Session.getDefaultInstance(props);
        List<EmailVo> emailVos = new ArrayList<>();
        try {
            IMAPStore store = (IMAPStore)session.getStore("imap");
            store.connect("zhengtianliang156@163.com", "LHvwWArkg8ptRTaw");
            store.id(IAM);



            IMAPFolder folderInbox = (IMAPFolder)store.getFolder("INBOX");
            folderInbox.open(Folder.READ_WRITE);

            Flags seenFlag = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seenFlag, false);
            Message[] messages = folderInbox.search(unseenFlagTerm);

//            Message[] messages = folderInbox.getMessages();
            for (int num = 0; num < messages.length; num++) {
                Message message = messages[num];
                if(Objects.isNull(message)){
                    continue;
                }
                EmailVo emailVo = parseEmail(message);
                if(Objects.isNull(emailVo) ||
                        (Objects.isNull(emailVo.getOfdBytes()) &&
                                Objects.isNull(emailVo.getPdfBytes()))){
                    continue;
                }
                emailVo.setMsgId(folderInbox.getUID(message));
                emailVos.add(emailVo);
            }
            // disconnect
            folderInbox.close(false);
            store.close();
        }
        catch (MessagingException | IOException e) {
            System.out.println(123123123);
        }
        return Result.success(emailVos);

    }






}
